package simple_bbs.security;

import act.aaa.ActAAAService;
import act.aaa.DynamicPermissionCheckHelperBase;
import act.db.morphia.MorphiaDao;
import org.osgl.aaa.Auditor;
import org.osgl.aaa.Principal;
import org.osgl.util.C;
import org.osgl.util.E;
import org.rythmengine.utils.S;
import simple_bbs.model.Audit;
import simple_bbs.model.User;
import simple_bbs.model.UserLinked;

import javax.inject.Inject;
import java.util.Set;

public class AppSecurity extends ActAAAService.Base<User> {

    public static final String PERM_CREATE = "create";
    public static final String PERM_UPDATE = "update";
    public static final String PERM_DELETE = "delete";

    private static final Set<String> DEFAULT_PERMS = C.set(PERM_CREATE, PERM_DELETE, PERM_UPDATE);

    @Override
    protected String userKey() {
        return "email";
    }

    @Override
    protected Set<String> permissionsOf(User user) {
        return DEFAULT_PERMS;
    }

    @Override
    protected boolean verifyPassword(User user, char[] password) {
        throw E.unsupport("Sorry, we use github to authenticate user");
    }

    public static class DynamicPermissionChecker extends DynamicPermissionCheckHelperBase<UserLinked> {
        @Override
        public boolean isAssociated(UserLinked userLinked, Principal principal) {
            return S.eq(userLinked.userId(), principal.getName());
        }
    }

    public static class TodoAuditor implements Auditor {

        @Inject
        private MorphiaDao<Audit> dao;

        @Override
        public void audit(Object target, Principal principal, String permission, String privilege, boolean success, String message) {
            dao.save(new Audit(target, principal, permission, success, message));
        }
    }
}
